package com.luoxue.mito.util;

import com.luoxue.mito.entity.BaseEntity;
import com.luoxue.mito.entity.MitoPost;
import com.luoxue.mito.entity.User;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public class MitoUtil {
    private static final String likeFormat = "%%%s%%";

    public static <T> T getValueOrDefault(T value, T defaultValue) {
        return value != null ? value : defaultValue;
    }


    public static String likeContact(String value){
        return String.format(MitoUtil.likeFormat, value);
    }

    public static <T extends BaseEntity, ID> Page<T> findAll(JpaRepository<T, ID> repository, T entity, ExampleMatcher exampleMatcher, Sort sort) {
        Integer reqPageNum = entity.getPageNum();
        if (reqPageNum != null && reqPageNum > 0) {
            reqPageNum--;
        }
        Example<T> example = Example.of(entity, exampleMatcher);
        Integer pageNum = MitoUtil.getValueOrDefault(reqPageNum, 0);
        Integer pageSize = MitoUtil.getValueOrDefault(entity.getPageSize(), 20);
        PageRequest pageable = PageRequest.of(pageNum, pageSize, sort);
        return repository.findAll(example, pageable);
    }

    public static <T extends BaseEntity> Page<T> findAll(JpaSpecificationExecutor<T> repository, T entity, Specification<T> specification, Sort sort) {
        Integer reqPageNum = entity.getPageNum();
        if (reqPageNum != null && reqPageNum > 0) {
            reqPageNum--;
        }
        Integer pageNum = MitoUtil.getValueOrDefault(reqPageNum, 0);
        Integer pageSize = MitoUtil.getValueOrDefault(entity.getPageSize(), 20);
        PageRequest pageable = PageRequest.of(pageNum, pageSize, sort);
        return repository.findAll(specification, pageable);
    }

    public static <T extends BaseEntity, ID> Page<T> findAll(JpaRepository<T, ID> repository, T entity, ExampleMatcher exampleMatcher) {
        return findAll(repository, entity, exampleMatcher, null);
    }

    public static <T extends BaseEntity, ID> Page<T> findAll(JpaRepository<T, ID> repository, T entity) {
        return findAll(repository, entity, null);
    }
}
